package jobhunter.security;

import jobhunter.model.User;
import jobhunter.repository.UserRepository;
import jobhunter.service.UserService;
import jobhunter.tool.ContextUtil;
import jobhunter.tool.SecurityUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class SecurityService {

    @Autowired  UserRepository userRepository ;
    @Autowired  UserService userService ;

    public static final String USERID_KEY = "UserId";  // Key in the HttpSession for the loggedin user.
    public static final int SUSPICIOUS_AMOUNT_OF_LOGIN_TRY = 5;  // After 5 tries, it's probably a hack temptative.

    public User login(String identifier, String clearPassword)
    {
        return loginEncrypted(identifier, SecurityUtils.myEncode(clearPassword == null ? "" : clearPassword));
    }

    public User loginEncrypted(String identifier, String md5Password) 
    {
        User user;
        if (identifier != null) 
        {
            user = identifyUserByUserName(identifier);
        } 
        else 
        {
            throw new IllegalArgumentException("Either localId () or identifier ("+identifier+") should not be null");
        }

        if(md5Password != null) 
        {
            assertPasswordValid(user, md5Password);
        }

        ContextUtil.getHttpSession().setAttribute(USERID_KEY, user.getId());
        ContextUtil.getHttpSession().setMaxInactiveInterval(7200);

        userRepository.merge(user);

        return user;
    }


    public User identifyUserByUserName(String identifier) 
    {

        User result;
        if (identifier == null) {
            throw new IllegalArgumentException("identifier is null");
        }

        identifier = identifier.toLowerCase();

        result = userRepository.findByUserName(identifier);


        if (result == null) {
            throw new RuntimeException(identifier);
        }
        return result;
    }


    public void logout() {
        ContextUtil.getHttpSession().invalidate();
        ContextUtil.getHttpServletRequest().getSession(true);
        SecurityContext.clear();       
    }


    public boolean assertPasswordValid(User user, String md5Password)
    {   
    	System.out.println(md5Password);
        if ( !md5Password.equalsIgnoreCase(user.getPassword())) 
        {  // Wrong password (not the same as DB or not in dev mode)

            userRepository.merge(user);
            throw new RuntimeException(user.getUsername());
        }
        // If we reach this point, the password is ok.
        return true;
    }
    public Long getLoggedInUserIdFromSession() {
        System.out.println("is in web request processing thread : "+ContextUtil.isInWebRequestProcessingThread());
        if (!ContextUtil.isInWebRequestProcessingThread()) 
        {
            return null;  // Nobody logged in during in batch jobs
        } else 
        { // normal web case
            return (Long) ContextUtil.getAttributFromHttpSession(USERID_KEY);
        }
    }
}
